package org.example.linkedList;

import java.util.Arrays;

/**
 * @Auther: wangbw @Date:2020/12/9 @Description: org.example.linkedList @version: 1.0
 */
public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = new int[]{4, 5, 3, 2, 8};
        sort(arr);
        print(arr);
        int[] arr1 = new int[]{4, 5, 3, 2, 8};
        sort2(arr1);
        print(arr1);
    }

    private static void sort(int[] arr) {
        if (arr == null || arr.length <= 1) return;
        for (int i = 1; i < arr.length; i++) {
            Integer temp = null;
            int temp2;
            for (int j = 0; j < i; j++)
                if (arr[i] < arr[j]) {                    /*腾出j所在的位置。*/
                    if (temp != null) {
                        temp2 = arr[j + 1];
                        arr[j + 1] = temp;
                        temp = temp2;
                    } else {
                        temp = arr[j + 1];
                        arr[j + 1] = arr[j];
                        arr[j] = arr[i];
                    }
                }
        }
    }

    private static void sort2(int[] arr) {
        if (arr == null || arr.length <= 1) return;
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j = i - 1;
            for (; j >= 0; j--) { /*4, 5, 3, 2, 8*/
                if (temp < arr[j]) arr[j + 1] = arr[j];
                else break;
            }
            arr[j + 1] = temp;
        }
    }

    private static void print(int[] arr) {
        System.out.println("result:" + Arrays.toString(arr));
    }
}
